from fastapi import FastAPI
import os
from pathlib import Path
from src.modules.knowbase.router import file_router,kb_router,tv_router,iv_router
from src.modules.chat.router import chat_router,chat_router2
from fastapi.middleware.cors import CORSMiddleware
from fastapi_pagination import Page, add_pagination
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
from core.config import settings
from src.modules.ai_models.model_loaders.model_loader import preload_models
from core.dependencies import get_redis, _redis

media_root_path = Path(settings.MEDIA_ROOT)
media_root_path.mkdir( exist_ok=True)  

# 创建容器实例
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup:应用启动时运行
    print("应用启动中...")
    # 例如：初始化数据库连接池，加载机器学习模型等
    preload_models()

    # 预先连接Redis(也可懒加载Redis)
    await get_redis()
    yield #此处是应用正常运行的时间点
    # Shutdown:应用关闭时运行
    print("应用关闭中...")

    # 例如：关闭数据库连接池，释放资源等


app = FastAPI(
    # 生命周期配置
    lifespan=lifespan,
    # 上传文件大小配置
    max_upload_size=100 * 1024 * 1024,  # 100MB
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应限制为具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
    )

app.mount(settings.MEDIA_URL, StaticFiles(directory=media_root_path), name="media")
add_pagination(app)
app.include_router(file_router.router)
app.include_router(kb_router.router)
app.include_router(tv_router.router)
app.include_router(iv_router.router)
app.include_router(chat_router.router)
app.include_router(chat_router2.router)


from src.modules.knowbase.services.containers import Container
container = Container()
# ✅ wire
container.wire(modules=[
    "src.modules.knowbase.router.file_router",
    "src.modules.knowbase.router.iv_router",
    "src.modules.knowbase.router.kb_router",
    "src.modules.knowbase.router.tv_router"
])

@app.get("/")
async def root():
    return {"message":"Hello World"}
